package com.example.controller;

import com.example.entity.TomcatServer;
import com.example.service.TomcatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Tomcat服务器管理控制器
 * 提供RESTful API接口，处理所有与Tomcat服务器相关的HTTP请求
 * 
 * @RestController: 标记这是一个REST控制器，所有方法返回JSON
 * @RequestMapping: 所有接口都以/api/tomcat为基础路径
 * @CrossOrigin: 允许跨域请求，用于前后端分离架构
 */
@RestController
@RequestMapping("/api/tomcat")
@CrossOrigin(origins = "*")
public class TomcatController {
    
    private static final Logger logger = LoggerFactory.getLogger(TomcatController.class);

    @Autowired
    private TomcatService tomcatService;

    /**
     * 测试接口
     * 用于验证API服务是否正常运行
     * 
     * @return 返回简单的成功消息
     */
    @GetMapping("/test")
    public ResponseEntity<String> test() {
        logger.info("Testing API endpoint");
        return ResponseEntity.ok("API is working!");
    }

    /**
     * 获取服务器列表
     * 支持分页和搜索功能
     * 
     * @param page 页码（从0开始）
     * @param size 每页显示的记录数
     * @param search 搜索关键字（可选）
     * @return 返回分页的服务器列表
     */
    @GetMapping("/list")
    public ResponseEntity<Page<TomcatServer>> getAllServers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        try {
            logger.info("Fetching servers page {} with size {} and search: {}", page, size, search);
            Page<TomcatServer> servers = tomcatService.findAll(PageRequest.of(page, size), search);
            logger.info("Found {} servers", servers.getTotalElements());
            return ResponseEntity.ok(servers);
        } catch (Exception e) {
            logger.error("Error fetching servers", e);
            throw e;
        }
    }

    /**
     * 创建新的Tomcat服务器
     * 
     * @param server 服务器信息，包含名称、地址、端口等
     * @return 返回创建成功的服务器信息
     */
    @PostMapping
    public ResponseEntity<TomcatServer> createServer(@RequestBody TomcatServer server) {
        try {
            logger.info("Creating new server: {}", server.getServerName());
            return ResponseEntity.ok(tomcatService.createServer(server));
        } catch (Exception e) {
            logger.error("Error creating server", e);
            throw e;
        }
    }

    /**
     * 删除指定的Tomcat服务器
     * 
     * @param id 服务器ID
     * @return 返回空响应，表示删除成功
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteServer(@PathVariable Long id) {
        try {
            logger.info("Deleting server with ID: {}", id);
            tomcatService.deleteServer(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("Error deleting server", e);
            throw e;
        }
    }

    /**
     * 重启指定的Tomcat服务器
     * 通过SSH连接到目标服务器执行重启命令
     * 
     * @param id 服务器ID
     * @return 返回重启操作的结果消息
     */
    @PostMapping("/restart/{id}")
    public ResponseEntity<String> restartServer(@PathVariable Long id) {
        try {
            logger.info("Restarting server with ID: {}", id);
            tomcatService.restartServer(id);
            return ResponseEntity.ok("Server restarted successfully");
        } catch (Exception e) {
            logger.error("Error restarting server", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 更新服务器信息
     * 
     * @param server 更新后的服务器信息
     * @return 返回更新后的服务器信息
     */
    @PutMapping("/update")
    public ResponseEntity<TomcatServer> updateServer(@RequestBody TomcatServer server) {
        try {
            logger.info("Updating server: {}", server.getServerName());
            return ResponseEntity.ok(tomcatService.updateServer(server));
        } catch (Exception e) {
            logger.error("Error updating server", e);
            throw e;
        }
    }

    /**
     * 获取Tomcat的catalina.out日志
     * 
     * @param id 服务器ID
     * @param lines 要获取的日志行数
     * @return 返回日志内容
     */
    @GetMapping("/{id}/logs")
    public ResponseEntity<String> getTomcatLogs(@PathVariable Long id, @RequestParam(defaultValue = "1000") int lines) {
        try {
            String logs = tomcatService.getTomcatLogs(id, lines);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            logger.error("Error fetching logs for server {}", id, e);
            return ResponseEntity.badRequest().body("Failed to fetch logs: " + e.getMessage());
        }
    }
} 